using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LF.Application.Extend;
using LF.Domain.Services;
using LF.Shared.Dtos.Out;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.ObjectMapping;

namespace LF.Application.Services.Iml
{
    [Authorize]
    [ApiExplorerSettings(GroupName = SwaggerGroup.Ai)]
    public class AIApplicationService : BaseService, IAIApplicationService
    {
        private readonly IAIService _aiService;
        private readonly IKnowledgeBaseManagerService _knowledgeBaseManager;

        public AIApplicationService(
            IObjectMapper<LFModule> mapper,
            IAIService aiService,
            IKnowledgeBaseManagerService knowledgeBaseManager,
            IGlobalManagerService globalManager) : base(mapper, globalManager)
        {
            _aiService = aiService;
            _knowledgeBaseManager = knowledgeBaseManager;
        }

        /// <summary>
        /// 处理知识库文件，生成向量嵌入
        /// </summary>
        [AllowAnonymous]
        [LFAuthorize("处理知识库文件", "knowledge:ai:process")]
        public async Task<Result> ProcessKnowledgeBaseAsync(Guid knowledgeBaseId, Guid? fileId = null)
        {
            // 验证知识库是否存在
            var knowledgeBase = _knowledgeBaseManager.GetKnowledgeBase(knowledgeBaseId);
            if (knowledgeBase == null)
                return Error("知识库不存在");

            // 如果指定了文件，验证文件是否存在且属于该知识库
            if (fileId.HasValue)
            {
                var file = _knowledgeBaseManager.GetKnowledgeFile(fileId.Value);
                if (file == null)
                    return Error("文件不存在");
                
                if (file.KnowledgeBaseId != knowledgeBaseId)
                    return Error("文件不属于该知识库");
            }

            // 调用领域服务处理文件
            var result = await _aiService.GenerateEmbeddingsAsync(knowledgeBaseId, fileId);
            if (result)
                return Ok("处理成功，文件已完成向量化");
            else
                return Error("处理失败，请检查文件是否正确上传");
        }
    }
} 